<template>
  <view class="flex-col page news-detail-page">
    <view class="flex-col section" :style="{ paddingTop: navHeight + 'px' }">
      <xlm-top-nav :scrollTop="scrollTop" title="新闻详情" />

      <view class="news-detail-content">
        <!-- 加载状态 -->
        <view v-if="loading" class="loading-container">
          <text class="loading-text">加载中...</text>
        </view>

        <!-- 错误状态 -->
        <view v-else-if="error" class="error-container">
          <text class="error-text">{{ error }}</text>
          <button @tap="getNewsDetail" class="retry-btn">重试</button>
        </view>

        <!-- 新闻内容 -->
        <view v-else-if="newsDetail" class="news-content">
          <!-- 标题 -->
          <view class="news-title">
            <text>{{ newsDetail.title }}</text>
          </view>

          <!-- 信息栏 -->
          <view class="news-info">
            <text class="news-time">{{ newsDetail.createtime }}</text>
            <text class="news-author" v-if="newsDetail.author">作者：{{ newsDetail.author }}</text>
            <view class="news-actions">
              <view class="action-btn" @click="onShare">
                <image :src="imgUrl + 'share2@2x.png'" class="action-icon" />
                <text class="action-text">分享</text>
              </view>
            </view>
          </view>

          <!-- 封面图片 -->
          <view v-if="newsDetail.cover_image" class="news-cover">
            <image :src="newsDetail.cover_image" mode="widthFix" class="cover-image" @error="onImageError" />
          </view>

          <!-- 新闻正文 -->
          <view class="news-body">
            <MpHtmlWrapper :content="newsDetail.content" :max-length="8000" @load="onMpHtmlLoad"
              @error="onMpHtmlError" />
          </view>

          <!-- 相关图片 -->
          <view v-if="newsDetail.images && newsDetail.images.length > 0" class="news-images">
            <view class="images-title">
              <text>相关图片</text>
            </view>
            <view class="images-grid">
              <view v-for="(image, index) in newsDetail.images" :key="index" class="image-item"
                @tap="previewImage(newsDetail.images, index)">
                <image :src="image" mode="aspectFill" class="grid-image" @error="onImageError" />
              </view>
            </view>
          </view>
        </view>

        <!-- 空状态 -->
        <view v-else class="empty-container">
          <text class="empty-text">暂无内容</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
  import { ref, computed, onMounted } from 'vue'
  import { imgUrl } from '@/utils/config'
  import { useOutsideAppStore } from '@/store/app'
  import { useRequest } from '@/api'
  import MpHtmlWrapper from '@/components/MpHtmlWrapper/MpHtmlWrapper.vue'
  import { ShareUtils, ShareConfigGenerator } from '@/utils/shareUtils.js'

  const appStore = useOutsideAppStore()
  const navHeight = computed(() => appStore.navHeight)
  const scrollTop = ref(0)

  const { API_NEWS_DETAIL_POST } = useRequest()

  // 页面数据
  const newsDetail = ref(null)
  const loading = ref(true)
  const error = ref('')
  const newsId = ref('')

  // 获取页面参数
  onMounted(() => {
    const pages = getCurrentPages()
    const currentPage = pages[pages.length - 1]
    const options = currentPage.options

    if (options.id) {
      newsId.value = options.id
      getNewsDetail()
    } else {
      error.value = '参数错误'
      loading.value = false
    }
  })

  // 获取新闻详情
  const getNewsDetail = async () => {
    try {
      loading.value = true
      error.value = ''

      // 测试数据，如果 API 不可用
      if (!API_NEWS_DETAIL_POST) {
        // 模拟数据用于测试
        setTimeout(() => {
          newsDetail.value = {
            id: newsId.value,
            title: '测试新闻标题',
            content: '<h1>测试新闻内容</h1><p>这是一个测试新闻的详细内容，用于验证页面功能是否正常。</p><p>新闻内容可以包含HTML标签，支持富文本显示。</p>',
            createtime: '2024-01-01 12:00:00',
            author: '测试作者',
            cover_image: imgUrl + 'a.jpg',
            images: [imgUrl + 'b.jpg', imgUrl + 'c.jpg']
          }
          loading.value = false
        }, 1000)
        return
      }

      const res = await API_NEWS_DETAIL_POST({ id: newsId.value })
      console.log('getNewsDetail', res)

      if (res.code === 1) {
        newsDetail.value = res.data
      } else {
        error.value = res.msg || '获取新闻详情失败'
        uni.showToast({ title: res.msg, icon: 'none' })
      }
    } catch (err) {
      console.error('获取新闻详情失败:', err)
      error.value = '网络错误'
      uni.showToast({ title: '网络错误', icon: 'none' })
    } finally {
      loading.value = false
    }
  }

  // HTML 渲染成功
  const onMpHtmlLoad = () => {
    console.log('新闻内容渲染成功')
  }

  // HTML 渲染失败
  const onMpHtmlError = (err) => {
    console.error('新闻内容渲染失败:', err)
  }

  // 图片加载失败
  const onImageError = (e) => {
    console.error('图片加载失败:', e)
  }

  // 预览图片
  const previewImage = (images, current) => {
    uni.previewImage({
      urls: images,
      current: current
    })
  }

  // 页面滚动
  const onPageScroll = (e) => {
    scrollTop.value = e.detail.scrollTop
  }

  // 分享功能
  const onShare = () => {
    if (!newsDetail.value) return

    const shareConfig = ShareConfigGenerator.generateNewsDetailShareConfig(newsDetail.value)
    ShareUtils.share(shareConfig)
  }

  // 微信小程序分享配置
  // 分享给好友
  const onShareAppMessage = () => {
    if (!newsDetail.value) return {}
    
    const shareData = {
      title: newsDetail.value.title || '新闻详情',
      desc: newsDetail.value.content ? newsDetail.value.content.replace(/<[^>]+>/g, '').substring(0, 100) + '...' : '点击查看新闻详情',
      path: `/pages/news/detail?id=${newsDetail.value.id}`,
      imageUrl: newsDetail.value.cover_image || ''
    }
    
    ShareUtils.recordShareEvent('share_to_friend', shareData)
    return shareData
  }
  
  // 分享到朋友圈
  const onShareTimeline = () => {
    if (!newsDetail.value) return {}
    
    const shareData = {
      title: newsDetail.value.title || '新闻详情',
      query: `id=${newsDetail.value.id}`,
      imageUrl: newsDetail.value.cover_image || ''
    }
    
    ShareUtils.recordShareEvent('share_to_timeline', shareData)
    return shareData
  }
</script>

<style lang="scss" scoped>
  .news-detail-page {
    background: #f5f5f5;
    min-height: 100vh;
  }

  .news-detail-content {
    padding: 24rpx;
  }

  .loading-container,
  .error-container,
  .empty-container {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 400rpx;

    .loading-text,
    .error-text,
    .empty-text {
      font-size: 28rpx;
      color: #666;
    }

    .retry-btn {
      margin-top: 24rpx;
      padding: 16rpx 32rpx;
      background: #007aff;
      color: #fff;
      border-radius: 8rpx;
      font-size: 28rpx;
    }
  }

  .news-content {
    background: #fff;
    border-radius: 16rpx;
    padding: 32rpx;
    margin-bottom: 24rpx;
  }

  .news-title {
    margin-bottom: 24rpx;

    text {
      font-size: 36rpx;
      font-weight: 600;
      color: #333;
      line-height: 1.4;
    }
  }

  .news-info {
    display: flex;
    align-items: center;
    margin-bottom: 24rpx;
    padding-bottom: 24rpx;
    border-bottom: 1rpx solid #f0f0f0;

    .news-time {
      font-size: 24rpx;
      color: #999;
      margin-right: 24rpx;
    }

    .news-author {
      font-size: 24rpx;
      color: #666;
    }

    .news-actions {
      display: flex;
      align-items: center;
      margin-left: 24rpx;

      .action-btn {
        display: flex;
        align-items: center;
        margin-left: 24rpx;

        .action-icon {
          width: 40rpx;
          height: 40rpx;
          margin-right: 8rpx;
        }

        .action-text {
          font-size: 24rpx;
          color: #007aff;
        }
      }
    }
  }

  .news-cover {
    margin-bottom: 24rpx;

    .cover-image {
      width: 100%;
      border-radius: 8rpx;
    }
  }

  .news-body {
    margin-bottom: 32rpx;
  }

  .news-images {
    .images-title {
      margin-bottom: 16rpx;

      text {
        font-size: 28rpx;
        font-weight: 600;
        color: #333;
      }
    }

    .images-grid {
      display: flex;
      flex-wrap: wrap;
      gap: 16rpx;

      .image-item {
        width: calc(50% - 8rpx);

        .grid-image {
          width: 100%;
          height: 200rpx;
          border-radius: 8rpx;
        }
      }
    }
  }
</style>